import { OptimizedImage } from './OptimizedImage';

export class OptimizedHomepage {
  private container: HTMLDivElement;

  constructor() {
    this.container = document.createElement('div');
    this.container.className = 'optimized-homepage';
    this.initContent();
  }

  private initContent() {
    this.container.innerHTML = `
      <!-- Header -->
      <header class="jd-header">
        <div class="header-top">
          <div class="container">
            <div class="location">
              <span>📍 北京</span>
            </div>
            <div class="user-menu">
              <a href="#">你好，请登录</a>
              <a href="#">免费注册</a>
              <a href="#">我的订单</a>
              <a href="#">我的京东</a>
              <a href="#">京东会员</a>
              <a href="#">企业采购</a>
              <a href="#">客户服务</a>
            </div>
          </div>
        </div>
        
        <div class="header-main">
          <div class="container">
            <div class="logo">
              <div class="logo-text">京东</div>
            </div>
            <div class="search-box">
              <input type="text" placeholder="搜索商品">
              <button class="search-btn">搜索</button>
            </div>
            <div class="cart">
              <span class="cart-icon">🛒</span>
              <span class="cart-text">我的购物车</span>
              <span class="cart-count">0</span>
            </div>
          </div>
        </div>
      </header>

      <!-- Navigation -->
      <nav class="jd-nav">
        <div class="container">
          <div class="nav-categories">
            <span class="nav-item">全部商品分类</span>
            <span class="nav-item">服装城</span>
            <span class="nav-item">美妆馆</span>
            <span class="nav-item">京东超市</span>
            <span class="nav-item">生鲜</span>
            <span class="nav-item">到家</span>
            <span class="nav-item">充值缴费</span>
            <span class="nav-item">9.9元拼</span>
            <span class="nav-item">领券</span>
            <span class="nav-item">领金贴</span>
            <span class="nav-item">plus会员</span>
          </div>
        </div>
      </nav>

      <!-- Main Content -->
      <main class="jd-main">
        <div class="container">
          <div class="main-content">
            <!-- Left Sidebar -->
            <aside class="sidebar">
              <div class="category-menu">
                <div class="category-item">
                  <span>📱 手机数码</span>
                  <span class="arrow">></span>
                </div>
                <div class="category-item">
                  <span>💻 电脑办公</span>
                  <span class="arrow">></span>
                </div>
                <div class="category-item">
                  <span>🏠 家用电器</span>
                  <span class="arrow">></span>
                </div>
                <div class="category-item">
                  <span>👕 服装鞋包</span>
                  <span class="arrow">></span>
                </div>
                <div class="category-item">
                  <span>💄 美妆护肤</span>
                  <span class="arrow">></span>
                </div>
                <div class="category-item">
                  <span>🍎 生鲜食品</span>
                  <span class="arrow">></span>
                </div>
                <div class="category-item">
                  <span>🏠 家居建材</span>
                  <span class="arrow">></span>
                </div>
                <div class="category-item">
                  <span>🚗 汽车用品</span>
                  <span class="arrow">></span>
                </div>
                <div class="category-item">
                  <span>🎮 运动户外</span>
                  <span class="arrow">></span>
                </div>
                <div class="category-item">
                  <span>📚 图书音像</span>
                  <span class="arrow">></span>
                </div>
              </div>
            </aside>

            <!-- Banner Section -->
            <section class="banner-section">
              <div class="main-banner" id="main-banner">
                <!-- 主轮播图将通过JavaScript动态加载 -->
              </div>
              <div class="banner-side">
                <div class="side-banner" id="side-banner-1">
                  <!-- 侧边广告1将通过JavaScript动态加载 -->
                </div>
                <div class="side-banner" id="side-banner-2">
                  <!-- 侧边广告2将通过JavaScript动态加载 -->
                </div>
              </div>
            </section>
          </div>
        </div>
      </main>

      <!-- Featured Products -->
      <section class="featured-products">
        <div class="container">
          <h2 class="section-title">热门商品</h2>
          <div class="product-grid" id="product-grid">
            <!-- 商品卡片将通过JavaScript动态生成 -->
          </div>
        </div>
      </section>

      <!-- Footer -->
      <footer class="jd-footer">
        <div class="container">
          <div class="footer-content">
            <div class="footer-section">
              <h4>购物指南</h4>
              <ul>
                <li><a href="#">购物流程</a></li>
                <li><a href="#">会员介绍</a></li>
                <li><a href="#">常见问题</a></li>
              </ul>
            </div>
            <div class="footer-section">
              <h4>配送方式</h4>
              <ul>
                <li><a href="#">上门自提</a></li>
                <li><a href="#">211限时达</a></li>
                <li><a href="#">配送服务查询</a></li>
              </ul>
            </div>
            <div class="footer-section">
              <h4>支付方式</h4>
              <ul>
                <li><a href="#">货到付款</a></li>
                <li><a href="#">在线支付</a></li>
                <li><a href="#">分期付款</a></li>
              </ul>
            </div>
            <div class="footer-section">
              <h4>售后服务</h4>
              <ul>
                <li><a href="#">售后政策</a></li>
                <li><a href="#">价格保护</a></li>
                <li><a href="#">退款说明</a></li>
              </ul>
            </div>
          </div>
        </div>
      </footer>
    `;

    // 延迟加载图片内容
    this.loadImagesLazily();
  }

  private loadImagesLazily(): void {
    // 使用 requestIdleCallback 在浏览器空闲时加载图片
    if ('requestIdleCallback' in window) {
      requestIdleCallback(() => this.loadBannerImages());
      requestIdleCallback(() => this.loadProductImages());
    } else {
      // 降级处理：使用 setTimeout
      setTimeout(() => this.loadBannerImages(), 100);
      setTimeout(() => this.loadProductImages(), 200);
    }
  }

  private loadBannerImages(): void {
    // 加载主轮播图
    const mainBanner = document.getElementById('main-banner');
    if (mainBanner) {
      const bannerImage = new OptimizedImage(
        this.generateLocalImageUrl('banner', 800, 400),
        '主轮播图',
        800,
        400,
        'main-banner-image'
      );
      mainBanner.appendChild(bannerImage.render());
    }

    // 加载侧边广告
    const sideBanner1 = document.getElementById('side-banner-1');
    const sideBanner2 = document.getElementById('side-banner-2');

    if (sideBanner1) {
      const sideImage1 = new OptimizedImage(
        this.generateLocalImageUrl('ad1', 200, 200),
        '侧边广告1',
        200,
        200,
        'side-banner-image'
      );
      sideBanner1.appendChild(sideImage1.render());
    }

    if (sideBanner2) {
      const sideImage2 = new OptimizedImage(
        this.generateLocalImageUrl('ad2', 200, 200),
        '侧边广告2',
        200,
        200,
        'side-banner-image'
      );
      sideBanner2.appendChild(sideImage2.render());
    }
  }

  private loadProductImages(): void {
    const productGrid = document.getElementById('product-grid');
    if (!productGrid) return;

    const products = [
      { name: 'Apple iPhone 15 Pro', desc: '钛金属设计，A17 Pro芯片', price: '¥7999', originalPrice: '¥8999' },
      { name: '华为 Mate 60 Pro', desc: '卫星通讯，昆仑玻璃', price: '¥6999', originalPrice: '¥7999' },
      { name: '小米14 Ultra', desc: '徕卡光学，骁龙8 Gen 3', price: '¥5999', originalPrice: '¥6499' },
      { name: 'MacBook Pro 14', desc: 'M3芯片，专业级性能', price: '¥14999', originalPrice: '¥15999' }
    ];

    products.forEach((product, index) => {
      const productCard = document.createElement('div');
      productCard.className = 'product-card';
      productCard.innerHTML = `
        <div class="product-image" id="product-image-${index}"></div>
        <div class="product-info">
          <h3 class="product-title">${product.name}</h3>
          <p class="product-desc">${product.desc}</p>
          <div class="product-price">
            <span class="current-price">${product.price}</span>
            <span class="original-price">${product.originalPrice}</span>
          </div>
        </div>
      `;

      productGrid.appendChild(productCard);

      // 延迟加载商品图片
      setTimeout(() => {
        const imageContainer = document.getElementById(`product-image-${index}`);
        if (imageContainer) {
          const productImage = new OptimizedImage(
            this.generateLocalImageUrl(`product${index + 1}`, 200, 200),
            product.name,
            200,
            200,
            'product-image'
          );
          imageContainer.appendChild(productImage.render());
        }
      }, index * 100); // 错开加载时间
    });
  }

  private generateLocalImageUrl(type: string, width: number, height: number): string {
    // 生成本地SVG图片URL，避免外部资源依赖
    const colors = {
      banner: '#ff6b6b',
      ad1: '#4ecdc4',
      ad2: '#45b7d1',
      product1: '#ff6b6b',
      product2: '#4ecdc4',
      product3: '#45b7d1',
      product4: '#96ceb4'
    };

    const color = colors[type as keyof typeof colors] || '#f0f0f0';
    const text = type.charAt(0).toUpperCase() + type.slice(1);

    return `data:image/svg+xml;base64,${btoa(`
      <svg width="${width}" height="${height}" xmlns="http://www.w3.org/2000/svg">
        <rect width="100%" height="100%" fill="${color}"/>
        <text x="50%" y="50%" font-family="Arial, sans-serif" font-size="16" 
              fill="white" text-anchor="middle" dy=".3em">${text}</text>
      </svg>
    `)}`;
  }

  public render(): HTMLElement {
    return this.container;
  }
} 